<template>
  <div class='amap-page-container'>
    <span>test</span>
    <el-amap vid='amapDemo'
             ref='map'
             :zoom='zoom'
             :events='events'
             :amap-manager='amapManager'
             :center='center'
             class='amap-demo'>
      <el-amap-polygon v-for='(polygon, index) in polygons'
                       :vid="'ploy'+index"
                       :key="'ploys'+index"
                       :ref='`polygon_${index}`'
                       :path='polygons.path'
                       fillColor='#0DAAFC'
                       strokeColor='#00A1E9'
                       :fillOpacity='0.3'></el-amap-polygon>
      <el-amap-marker v-for='(marker, index) in markers'
                      :position='marker.position'
                      :vid='index'
                      :key="'marker' + index"
                      :editable='true'
                      :draggable='true'
                      :events='marker.events'></el-amap-marker>
    </el-amap>
  </div>
</template>


<script>
import { AMapManager } from 'vue-amap'

let amapManager = new AMapManager()//获取高德原生 AMap.Map
export default {
  name: 'map2',
  data() {
    return {
      amapManager,
      zoom: 12,
      center: [121.5273285, 31.21515044],
      events: {
        click: (e) => {
          this.setLang(e)
        }
      },
      markers: [], //标注

      polygons: {
        path: []
      }, //折线
      curMark: [] //当前路径
    }
  },
  methods: {

    //设置坐标的信息
    setLang(e) {
      let newLat = [e.lnglat.lng, e.lnglat.lat]
      this.setData(newLat)
    },
    //设备图标坐标(参数二：不添加多边形)
    setData(elem, type) {
      let index = this.markers.length
      this.markers.push({
        position: elem,
        events: {
          dragend: (e) => {
            this.dragend(e, index)
          },
          click: (e) => {
            this.deleceData(index)
          }
        }
      })
      if (!type) {
        this.polygons.path.push(elem)
        this.curMark.push(elem)
      }
    },
    //拖拽地图
    dragend(e, index) {
      //获取当前被改变的经纬度信息
      let newData = [e.lnglat.lng, e.lnglat.lat]
      let newList = JSON.parse(JSON.stringify(this.curMark))
      newList[index] = newData
      this.markers[index].position = newData
      this.curMark[index] = newData
      //重新绘制多边形信息
      this.polygons.path = []
      this.polygons.path = newList.map(elem => {
        return elem
      })
    },
    //删除地图坐标
    deleceData(index) {
      this.curMark.splice(index, 1)
      this.polygons.path.splice(index, 1)
      this.markers = []
      let newList = JSON.parse(JSON.stringify(this.curMark))
      //重新绘制坐标信息
      newList.forEach((elem, i) => {
        this.setData(elem, true)
      })
    },
    //重置坐标点的选中
    resetMark() {
      this.markers = []
      this.curMark = []
      this.polygons.path = []
    }
  }
}
</script>
<style scoped>
.amap-page-container,
.amap-demo {
  height: 100%;
}
</style>


